<template>
  <!-- ... existing code ... -->
  <el-form 
    ref="formRef"
    :model="formData"
    :rules="rules" <!-- 确保 rules 已定义 -->
    label-width="220px"
    class="form-content"
    v-loading="loading"
  >
    <!-- ... existing code ... -->
  </el-form>
  <!-- ... existing code ... -->
  <div class="button-group">
    <el-button type="primary" @click="handleNextStep">保 存</el-button>
    <!-- ... existing code ... -->
  </div>
  <!-- ... existing code ... -->
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { closeLoopDetailNodes, closeLoopDetailYzBase, closeLoopDetailCloumn } from '@/stores/closeLoopList';

// 新增：定义 rules
const rules = reactive({
  NODE_NAME: [
    { required: true, message: '医嘱中文名称不能为空', trigger: 'blur' },
  ],
  BASE_TABLE_NAME: [
    { required: true, message: '医嘱英文名称不能为空', trigger: 'blur' },
  ],
});

const closeLoopStore = closeLoopDetailNodes();
const closeLoopBaseStore = closeLoopDetailYzBase();
const closeLoopColumnStore = closeLoopDetailCloumn();

const route = useRoute();
const NODE_ID = route.query.NODE_ID;

const loading = ref(false);
const formData = reactive({
  NODE_NAME: '',
  BASE_TABLE_NAME: '',
  dataSourceId: '-1',
  HAVE_MANY_TIMES: 0,
});

const configFields = [
  { fieldName: 'id', label: 'ID', value: '' },
  { fieldName: 'name', label: '名称', value: '' },
  { fieldName: 'description', label: '描述', value: '' },
  { fieldName: 'status', label: '状态', value: '' },
  { fieldName: 'created_at', label: '创建时间', value: '' },
  { fieldName: 'updated_at', label: '更新时间', value: '' },
];

const fetchData = async () => {
  if (!NODE_ID) {
    console.error('NODE_ID 参数为空，无法发起请求');
    ElMessage.error('缺少闭环ID，请检查路由参数');
    return;
  }
  loading.value = true;
  try {
    // 1. 获取闭环详情（主数据）
    await closeLoopStore.getCloseLoopDeatilNodes(NODE_ID); // 获取闭环详情
    // 2. 更新表单数据
    Object.assign(formData, {
      ...closeLoopStore.closeLoopDeatilNodesList[0] || {},
      dataSourceId: closeLoopStore.closeLoopDeatilNodesList[0]?.BASE_ID || '-1',
      HAVE_MANY_TIMES: Number(closeLoopStore.closeLoopDeatilNodesList[0]?.HAVE_MANY_TIMES) || 0,
    });
    // 3. 获取数据源列表
    await closeLoopBaseStore.fetchCloseLoopBaseList();
    // 4. 获取字段配置
    await closeLoopColumnStore.getCloseLoopDeatilList(NODE_ID);
    // 5. 初始化 configFields 的 value
    let columnList = closeLoopColumnStore.closeLoopDeatilColumnList || [];
    if (!Array.isArray(columnList)) {
      columnList = [];
    }
    const columnMap = {};
    columnList.forEach(item => {
      const lowerColumnName = item.COLUMN_NAME.toLowerCase();
      columnMap[lowerColumnName] = item.COLUMN_SQL || '';
    });
    configFields.forEach(field => {
      field.value = columnMap[field.fieldName] || '';
    });
    configFields.sort((a, b) => {
      const orderA = columnList.find(
        item => item.COLUMN_NAME === a.fieldName.toUpperCase()
      )?.ORDER_NUM || 0;
      const orderB = columnList.find(
        item => item.COLUMN_NAME === b.fieldName.toUpperCase()
      )?.ORDER_NUM || 0;
      return parseInt(orderA, 10) - parseInt(orderB, 10);
    });
  } catch (error) {
    console.error('获取闭环详情失败:', error); // 增强错误日志
    ElMessage.error(`获取数据失败: ${error.message || '未知错误'}`);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});

// 新增：实现 handleNextStep 方法
const handleNextStep = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功');
      // 可以在这里添加保存逻辑
    } else {
      ElMessage.error('表单验证失败，请检查输入');
    }
  });
};

</script>

<style scoped>
/* ... existing code ... */
</style>